package com.example.shop.service.serviceImpl;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.shop.mapper.AreaCodeMapper;
import com.example.shop.mapper.UserEducationMapper;
import com.example.shop.mapper.UserMapper;
import com.example.shop.pojo.User;
import com.example.shop.pojo.UserDto;
import com.example.shop.pojo.UserEducation;
import com.example.shop.service.UserService;
import com.example.shop.utils.BaseContext;
import com.example.shop.utils.UserIdSession;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserEducationMapper userEducationMapper;
	@Autowired
	private AreaCodeMapper areaCodeMapper;

	/**
	 * 用户注册
	 * 
	 * @throws SQLException
	 */
	@Override
	public String register(User user) throws Exception {
		if (userMapper.selectByAccount(user.getAccount()) != null) {
			return "用户已经注册";
		}
		// 校验数据
		if (user.getAccount() == null && user.getUserName() == null && user.getPassword() == null) {
			return "账号、姓名、密码不能为空";
		}

		// 完善用户信息
		user.setPassword(encryptPassword(user.getPassword()));
		/*
		 * user.setDeviceNumber("vivo-iqoo-neo5");
		 * user.setCreatedDate(LocalDateTime.now());
		 */
		user.setIpAddr(getInternalIP());

		// System.out.println(userMapper.save(user));

		if (userMapper.save(user) > 0) {
			return "注册成功";
		}
		return "注册异常";

	}

	/**
	 * 普通用户登录
	 */
	@Override
	public String login(User user) {
		// 根账号获取user
		User newUser = userMapper.selectByAccount(user.getAccount());

		// 检验数据
		if (user.getAccount() == null && user.getPassword() == null) {
			return "账号、姓名、密码不能为空";
		}
		if (!encryptPassword(user.getPassword()).equals(newUser.getPassword())
				&& !user.getIpAddr().equals(newUser.getIpAddr())) {
			return "密码不正确或ip非法";
		}

		// 将用户id保存到session和ThreadLocal
		UserIdSession.setAttribute(user.getAccount(), user.getAccount());
		BaseContext.setAccountId(user.getAccount());
		BaseContext.setIphoneNum(user.getIphoneNum());
		// System.out.print(BaseContext.getAccountId());
		return "登录成功";
	}

	/**
	 * 用户信息认证
	 */
	@Override
	public String infoAuthentication(UserDto user) {

		// System.out.print(BaseContext.getAccountId());
		if (user.getIdentityCard() == null && user.getBankCardNumber() == null && user.getIphoneNum() == null
				&& user.getUserName() == null && user.getUserId() == null && user.getDegree() == null
				&& user.getUniversity() == null) {
			return "用户信息不完整";
		}

		// 检验身份证号
		if (isValidIDCard(user.getIdentityCard().toString())) {
			return "身份证号错误";
		}
		;
		// 检验银行卡号
		if (isValidBankCardNumber(user.getBankCardNumber())) {
			return "银行卡号格式错误";
		}
		;
		// 检验手机号
		if (isValidPhoneNumber(user.getIphoneNum().toString())) {
			return "手机号错误";
		}

		// 完善数据
		User newUser = userMapper.selectById((Long) UserIdSession.getAttribute(user.getAccount()));
		newUser.setIdentityCard(user.getIdentityCard());
		newUser.setBankCardNumber(user.getBankCardNumber());
		newUser.setIphoneNum(user.getIphoneNum());
		user.setGraduationYear(LocalDate.now().toString());

		// 保存信息
		userMapper.save(newUser);
		UserEducation userEducation = new UserEducation();
		BeanUtils.copyProperties(user, userEducation);
		if (userEducationMapper.save(userEducation) <= 0) {
			return "用户信息认证失败";
		}
		return "用户信息认证成功";

	}

	/**
	 * 用户信息认证1:姓名、身份证验证
	 */
	@Override
	public String infoAuthentication1(UserDto user) {
		System.out.println(user.toString());
		if (user.getIdentityCard() == null && user.getUserName() == null) {
			return "用户信息不完整";
		}

		System.out.println(user.getIdentityCard().toString().substring(0, 6));
		// 检验身份证号
		if (!isValidIDCard(user.getIdentityCard().toString().substring(0, 6))) {
			return "身份证号错误";
		}
		;

		// 完善数据
		User newUser = userMapper.selectByUserName(user.getUserName());
		newUser.setIdentityCard(user.getIdentityCard());

		// 保存信息
		userMapper.updateById(newUser);

		if (userMapper.updateById(newUser) <= 0) {
			return "用户信息认证失败";
		}
		return "用户信息认证成功";
	}

	/**
	 * 用户信息验证认证2:姓名、学历
	 */
	@Override
	public String infoAuthentication2(UserDto user) {
		System.out.println(user.toString());
		if (user.getUserName() == null && user.getUserId() == null && user.getDegree() == null
				&& user.getUniversity() == null && user.getMajor() == null) {
			return "用户信息不完整";
		}

		// 完善数据
		user.setGraduationYear(LocalDate.now().toString());

		// 保存信息
		UserEducation userEducation = new UserEducation();
		BeanUtils.copyProperties(user, userEducation);

		System.out.println(userEducation.toString());

		userEducationMapper.updateByUserId(userEducation);
		if (userEducationMapper.updateByUserId(userEducation) <= 0) {
			return "用户信息认证失败";
		}
		return "用户信息认证成功";

	}

	/**
	 * 用户信息认证3:有无犯罪记录
	 */
	@Override
	public String infoAuthentication3(UserDto user) {
		System.out.print(BaseContext.getAccountId());
		if (user.getUserName() == null && user.getCriminalRecord() == null && user.getAccount() == null) {
			return "用户信息不完整";
		}

		// 检测是否犯罪
		User newUser = userMapper.selectByUserName(user.getUserName());
		if (newUser.getCriminalRecord() == 0) {
			return "用户没有犯罪记录";
		}
		return "用户有犯罪记录";

	}

	/**
	 * 用户信息认证4:姓名、身份证、银行卡验证
	 */
	@Override
	public String infoAuthentication4(UserDto user) {
		System.out.print(BaseContext.getAccountId());
		if (user.getIdentityCard() == null && user.getBankCardNumber() == null && user.getUserName() == null
				&& user.getAccount() == null) {
			return "用户信息不完整";
		}

		// 检验身份证号
		if (!isValidIDCard(user.getIdentityCard().toString().substring(0, 6))) {
			return "身份证号错误";
		}
		;
		// 检验银行卡号
		if (isValidBankCardNumber(user.getBankCardNumber())) {
			return "银行卡号格式错误";
		}
		;

		// 完善数据
		User newUser = userMapper.selectByUserName(user.getUserName());
		newUser.setIdentityCard(user.getIdentityCard());
		newUser.setBankCardNumber(user.getBankCardNumber());
		System.out.println(newUser.toString() + user.getIdentityCard());
		// 保存信息
		int i = userMapper.updateById(newUser);
		System.out.println(i);

		if (userMapper.updateById(newUser) <= 0) {
			return "用户信息认证失败";
		}
		return "用户信息认证成功";

	}

	/**
	 * 用户信息认证5:姓名、身份证、手机号验证
	 */
	@Override
	public String infoAuthentication5(UserDto user) {
		// System.out.print(BaseContext.getAccountId());
		if (user.getIdentityCard() == null && user.getIphoneNum() == null && user.getUserName() == null
				&& user.getUserId() == null && user.getAccount() == null) {
			return "用户信息不完整";
		}

		// 检验身份证号
		if (isValidIDCard(user.getIdentityCard().toString())) {
			return "身份证号错误";
		}
		;
		// 检验手机号
		if (isValidPhoneNumber(user.getIphoneNum().toString())) {
			return "手机号格式错误";
		}
		// 验证验证码
		if (!isValidPhoneAuthNumber(user.getIphoneNum().toString(), user.getCode())) {
			return "验证码错误";
		}
		// 完善数据
		User newUser = userMapper.selectByUserName(user.getUserName());
		newUser.setIdentityCard(user.getIdentityCard());
		newUser.setIphoneNum(user.getIphoneNum());

		// 保存信息
		userMapper.updateById(newUser);

		if (userMapper.updateById(newUser) <= 0) {
			return "用户信息认证失败";
		}
		return "用户信息认证成功";

	}

	/**
	 * 用户更新信息
	 */
	@Override
	public String updateInfo(User user, Object code) {
		// 校验数据
		if (user.getIphoneNum() == null && user.getPassword() == null && user.getIpAddr() == null
				&& user.getDeviceNumber() == null && user.getNickname() == null && user.getUserImage() == null
				&& code == null) {
			return "用户信息不完整";
		}

		// 验证密码是否正确
		User newUser = userMapper.selectByAccount(user.getAccount());
		if (user.getPassword().equals(newUser.getPassword())) {
			return "旧密码不正确";
		}
		// 验证手机验证码是否正确
		System.out.println(newUser.getIphoneNum().toString());
		Object phoneCode = UserIdSession.getAttribute(newUser.getIphoneNum().toString());
		if (phoneCode == null) {
			return "请发送验证码";
		}
		if (!phoneCode.equals(code)) {
			return "验证码错误";
		}

		// 准备数据
		user.setIpAddr(getInternalIP());
		if (userMapper.updateById(user) <= 0) {
			return "用户更新信息异常";
		}
		;
		return "用户成功更新信息";
	}

	/**
	 * MD5加密
	 * 
	 * @param password
	 * @return
	 */
	private String encryptPassword(String password) {
		try {
			// 创建 MessageDigest 实例并指定使用 MD5 算法
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			// 将密码转换为字节数组
			byte[] passwordBytes = password.getBytes();
			// 对密码进行加密
			byte[] encryptedBytes = messageDigest.digest(passwordBytes);

			// 将加密后的字节数组转换为十六进制字符串
			StringBuilder hexString = new StringBuilder();
			for (byte b : encryptedBytes) {
				String hex = Integer.toHexString(0xFF & b);
				if (hex.length() == 1) {
					hexString.append('0');
				}
				hexString.append(hex);
			}

			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取内网ip
	 * 
	 * @return
	 */
	private String getInternalIP() {
		String ip = "";
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface networkInterface = networkInterfaces.nextElement();
				Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					InetAddress address = addresses.nextElement();
					if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && address.isSiteLocalAddress()) {
						ip = address.getHostAddress();
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return ip;
	}

	/**
	 * 检验身份证号
	 */
	private boolean isValidIDCard(String idCard) {
		// 查询数据库获得所有地区号
		ArrayList<Long> lists = areaCodeMapper.selectAll();

		// 比对当前地区号是否存在
		for (Long list : lists) {
			if (idCard.equals(list.toString())) {
				return true;
			}
			// System.out.println(list + " " + idCard.equals(list));
		}
		return false;
	}

	/**
	 * 验证银行卡号
	 */
	private boolean isValidBankCardNumber(String bankCardNumber) {
		// 去除银行卡号中的空格和非数字字符
		String cleanBankCardNumber = bankCardNumber.replaceAll("\\s+", "").replaceAll("\\D", "");
		if (cleanBankCardNumber.length() < 12 || cleanBankCardNumber.length() > 19) {
			return false; // 银行卡号长度不符合要求
		}

		// 逆序处理银行卡号各位数字
		StringBuilder reversedNumber = new StringBuilder(cleanBankCardNumber).reverse();

		int sum = 0;
		for (int i = 0; i < reversedNumber.length(); i++) {
			int digit = Character.digit(reversedNumber.charAt(i), 10);
			if (i % 2 == 0) {
				digit *= 2;
				if (digit > 9) {
					digit -= 9;
				}
			}
			sum += digit;
		}

		return sum % 10 == 0;
	}

	/**
	 * 检验手机号
	 */
	private boolean isValidPhoneNumber(String phoneNumber) {
		// 手机号正则表达式，根据需要可以进行修改
		String regex = "^1[3456789]\\d{9}$";
		// 判断手机号是否匹配正则表达式
		return phoneNumber.matches(regex);
	}

	/**
	 * 检验手机验证码
	 */
	private boolean isValidPhoneAuthNumber(String iphoneNum, String code) {

		// 获取验证码
		String codeVaild = (String) UserIdSession.getAttribute(iphoneNum);
		if (code == null || codeVaild == null) {
			return false;
		}
		return codeVaild.equals(code);
	}

	/**
	 * 查询用户
	 */
	@Override
	public User selectUser(UserDto user) {
		// 校验数据
		if (user.getAccount() == null) {
			return null;
		}
		// 查询用户
		User u = userMapper.selectByAccount(user.getAccount());
		return u;
	}

}
